﻿/*  Copyright © 2012 Matthew David Elgert - mdelgert@yahoo.com
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation; either version 2.1 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */

using System;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Timers;
using System.Security.Principal;
using System.Security.AccessControl;

namespace BLL
{

    public static class Common
    {

        public static Timer tmr = new Timer();       

        private static string GetAssemblyVersion()
        {
            Version version = Assembly.GetExecutingAssembly().GetName().Version;
            return string.Format("{0}.{1}.{2}", version.Major, version.Minor, version.Build);
        }

        public static string GetDBBackupDir()
        {
            string GetDBBackupDir = @"\DBBackup\";
            return GetDBBackupDir;
        }

        public static string GetDBBackupFullPath(string DBName)
        {
            string DBBKFullPath = String.Format(@"{0}{1}{2}{3}", Common.GetTempDir(), DBName, Common.GetTimeStamp(), GetDBBackupDir());
            CreateDBBackupFullTemp(DBBKFullPath);
            return DBBKFullPath;
        }

        private static void CreateDBBackupFullTemp(string DBBKFullPath)
        {
            if (!Directory.Exists(DBBKFullPath))
            {
                try
                {
                    Directory.CreateDirectory(DBBKFullPath);
                }
                catch (System.Exception ex)
                {
                    Log.Msg(ex.ToString(), true);
                }
            }
        }

        public static string GetLogDB()
        {
            string LogDB;
            if (ConfigurationManager.AppSettings.Get("LogDB") != null)
                LogDB = ConfigurationManager.AppSettings.Get("LogDB");
            else
                LogDB = null;
            return LogDB;
        }

        public static string GetTempDir()
        {
            string TempDir;
            if (ConfigurationManager.AppSettings.Get("TempDir") != null)
            {
                TempDir = ConfigurationManager.AppSettings.Get("TempDir");
            }
            else
            {
                TempDir = Directory.GetCurrentDirectory() + @"\SQLBackupFTPTemp\";
            }
            return TempDir;
        }

        public static string GetTimeStamp()
        {
            string TimeStamp = ConfigurationManager.AppSettings.Get("TimeStamp");
            return TimeStamp;
        }

        public static string GetLogFile()
        {
            string LogFile = null;
            if (ConfigurationManager.AppSettings.Get("LogFile") != null)
            {
                LogFile = GetTempDir() + GetTimeStamp() + ConfigurationManager.AppSettings.Get("LogFile");
            }
            if (GetTimeStamp() != null)
            {
                LogFile = String.Format("{0}{1}Log.txt", GetTempDir(), GetTimeStamp());
            }
            return LogFile;
        }

        public static string GetLogTxt()
        {
            string text = null;
            try
            {
                string[] lines = File.ReadAllLines(Common.GetLogFile());
                foreach (string line in lines)
                {
                    text = String.Format("{0}\r\n{1}", text, line);
                }
            }
            catch (Exception ex)
            {
                Log.Msg(ex.ToString(), true);
            }
            return text;
        }

        public static string CreateTimeStamp()
        {
            DateTime value = DateTime.Now;
            return value.ToString("yyyyMMddHHmmss");
        }

        public static string GetArchivePwd()
        {
            string ArchivePwd;
            if (ConfigurationManager.AppSettings.Get("ArchivePwd") != null)
                ArchivePwd = ConfigurationManager.AppSettings.Get("ArchivePwd");
            else
                ArchivePwd = null;
            return ArchivePwd;
        }

        public static string GetSendEmailTo()
        {
            string SendEmailTo;
            if (ConfigurationManager.AppSettings.Get("SendEmailTo") != null)
            {
                SendEmailTo = ConfigurationManager.AppSettings.Get("SendEmailTo");
            }
            else
            {
                SendEmailTo = null;
            }
            return SendEmailTo;
        }

        public static string GetSendEmailFrom()
        {
            string SendEmailFrom;
            if (ConfigurationManager.AppSettings.Get("SendEmailFrom") != null)
            {
                SendEmailFrom = ConfigurationManager.AppSettings.Get("SendEmailFrom");
            }
            else
            {
                SendEmailFrom = GetSendEmailTo();
            }
            return SendEmailFrom;
        }

        public static string GetSendEmailSubject()
        {
            string SendEmailSubject;
            if (ConfigurationManager.AppSettings.Get("SendEmailSubject") != null)
            {
                SendEmailSubject = ConfigurationManager.AppSettings.Get("SendEmailSubject");
            }
            else
            {
                SendEmailSubject = "SQLBackupFTPLog";
            }
            return SendEmailSubject;
        }

        public static bool GetHasSMTPRelayHost()
        {
            bool HasSMTPRelayHost;
            if (ConfigurationManager.AppSettings.Get("SMTPRelayHost") != null)
                HasSMTPRelayHost = true;
            else
                HasSMTPRelayHost = false;
            return HasSMTPRelayHost;
        }

        public static bool GetScriptDB()
        {
            bool ScriptDB;
            if (ConfigurationManager.AppSettings.Get("ScriptDB") != null)
                ScriptDB = bool.Parse(ConfigurationManager.AppSettings.Get("ScriptDB"));
            else
                ScriptDB = false;
            return ScriptDB;
        }

        public static bool GetScriptTableData()
        {
            bool ScriptTableData;
            if (ConfigurationManager.AppSettings.Get("ScriptTableData") != null)
                ScriptTableData = bool.Parse(ConfigurationManager.AppSettings.Get("ScriptTableData"));
            else
                ScriptTableData = false;
            return ScriptTableData;
        }

        public static bool GetBackupAll()
        {
            bool BackupAll;
            if (ConfigurationManager.AppSettings.Get("BackupAll") != null)
                BackupAll = bool.Parse(ConfigurationManager.AppSettings.Get("BackupAll"));
            else
                BackupAll = false;
            return BackupAll;
        }

        public static bool GetDelTemp()
        {
            bool DelTemp;
            if (ConfigurationManager.AppSettings.Get("DelTemp") != null)
                DelTemp = bool.Parse(ConfigurationManager.AppSettings.Get("DelTemp"));
            else
                DelTemp = false;
            return DelTemp;
        }

        public static bool GetDelBakTemp()
        {
            bool DelBakTemp;
            if (ConfigurationManager.AppSettings.Get("DelBakTemp") != null)
                DelBakTemp = bool.Parse(ConfigurationManager.AppSettings.Get("DelBakTemp"));
            else
                DelBakTemp = false;
            return DelBakTemp;
        }

        public static bool GetConsoleExit()
        {
            bool ConsoleExit;
            if (ConfigurationManager.AppSettings.Get("ConsoleExit") != null)
                ConsoleExit = bool.Parse(ConfigurationManager.AppSettings.Get("ConsoleExit"));
            else
                ConsoleExit = false;
            return ConsoleExit;
        }

        public static bool GetBackupDBOff()
        {
            bool BackupDBOff;
            if (ConfigurationManager.AppSettings.Get("BackupDBOff") != null)
                BackupDBOff = bool.Parse(ConfigurationManager.AppSettings.Get("BackupDBOff"));
            else
                BackupDBOff = false;
            return BackupDBOff;
        }

        public static bool GetFTPOff()
        {
            bool FTPOff;
            if (ConfigurationManager.AppSettings.Get("FTPOff") != null)
                FTPOff = bool.Parse(ConfigurationManager.AppSettings.Get("FTPOff"));
            else
                FTPOff = false;
            return FTPOff;
        }

        public static bool GetSevenZipOff()
        {
            bool SevenZipOff;
            if (ConfigurationManager.AppSettings.Get("SevenZipOff") != null)
                SevenZipOff = bool.Parse(ConfigurationManager.AppSettings.Get("SevenZipOff"));
            else
                SevenZipOff = false;
            return SevenZipOff;
        }

        public static bool GetSendMailOff()
        {
            bool SendMailOff;
            if (ConfigurationManager.AppSettings.Get("SendMailOff") != null)
                SendMailOff = bool.Parse(ConfigurationManager.AppSettings.Get("SendMailOff"));
            else
                SendMailOff = false;
            return SendMailOff;
        }

        public static int GetFTPTimeOut()
        {
            int FTPTimeOut;
            if (ConfigurationManager.AppSettings.Get("FTPTimeOut") != null)
                FTPTimeOut = int.Parse(ConfigurationManager.AppSettings.Get("FTPTimeOut"));
            else
                FTPTimeOut = 120000;
            return FTPTimeOut;
        }

        public static int GetSQLCommandTimeout()
        {
            int SQLCommandTimeout;
            if (ConfigurationManager.AppSettings.Get("SQLCommandTimeout") != null)
                SQLCommandTimeout = int.Parse(ConfigurationManager.AppSettings.Get("SQLCommandTimeout"));
            else
                SQLCommandTimeout = 999999999;
            return SQLCommandTimeout;
        }

        public static DataTable GetDBNames()
        {
            DataTable dt = new DataTable();

            if (Common.GetBackupAll() != true)
            {

                try
                {
                    dt.Columns.Add("Database", typeof(string));
                    XmlDocument doc = new XmlDocument();
                    doc.Load("Databases.xml");
                    XmlNodeList nodes = doc.SelectNodes("XMLDocument/Database/DBName");

                    foreach (XmlNode node in nodes)
                    {
                        dt.Rows.Add(node.InnerText);
                    }

                }
                catch (Exception e)
                {
                    Log.Msg("Error: " + e, true);
                }

            }
            else
            {
                using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString()))
                {
                    try
                    {
                        StreamReader streamReader = new StreamReader("DBQuery.sql");
                        try
                        {
                            //Query all DB's from scripts
                            string sql = streamReader.ReadToEnd();
                            streamReader.Close();
                            cnn.Open();
                            SqlDataAdapter da = new SqlDataAdapter(sql, cnn);
                            da.Fill(dt);
                        }
                        finally
                        {
                            if (streamReader != null)
                                streamReader.Dispose();
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Msg("Error: " + e, true);
                    }
                    finally
                    {
                        cnn.Close();
                    }
                }
            }

            return dt;
        }

        public static void CreateTempDir()
        {
            try
            {
                if (!Directory.Exists(Common.GetTempDir()))
                {
                    Directory.CreateDirectory(Common.GetTempDir()); //Create dir
                }
            }
            catch (Exception ex)
            {
                Log.Msg(ex.ToString(), true);
            }
        }

        public static void ConsoleExit()
        {
            if (BLL.Common.GetConsoleExit() == false)
            {
                Console.ReadKey();
            }
        }

        public static void DeleteTempDir()
        {
            if (BLL.Common.GetDelTemp() == true)
            {
                try
                {
                    if (Directory.Exists(Common.GetTempDir()))
                    {
                        Directory.Delete(Common.GetTempDir(), true);
                    }
                }
                catch (Exception ex)
                {
                    Log.Msg(ex.ToString(), true);
                }
            }
        }

        public static void DeleteFileTemp(string DBName)
        {
            string TempFolderPath = Common.GetTempDir() + DBName + Common.GetTimeStamp();
            if (Directory.Exists(TempFolderPath.Replace(@"\\", @"\")))
            {
                try
                {
                    Directory.Delete(TempFolderPath.Replace(@"\\", @"\"), true);
                }
                catch (IOException e)
                {
                    Log.Msg(e.Message, true);
                    return;
                }
            }
        }

        public static void WriteTimeStamp()
        {
            Configuration Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            Config.AppSettings.Settings["TimeStamp"].Value = CreateTimeStamp();
            Config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        public static void ShowHeader()
        {
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Copyright (C) Matthew David Elgert 2012");
            Console.WriteLine("SQLBackupFTP version " + GetAssemblyVersion());
            Console.WriteLine();
            Console.WriteLine("http://sqlbackupftp.codeplex.com/");
            Console.WriteLine("mdelgert@yahoo.com");
            Console.WriteLine();
            Console.WriteLine("");
        }

        public static void ShowFooter()
        {
            Console.WriteLine("");
        }

        public static void ShowProgress(bool Show)
        {
            if (Show == true)
            {
                Console.WriteLine("");
                tmr.Interval = 1000;
                tmr.Elapsed += tmr_Elapsed;    // Uses an event instead of a delegate
                tmr.Start();
            }
            else
            {
                tmr.Stop();
                Console.WriteLine("");
            }
        }

        static void tmr_Elapsed(object sender, EventArgs e)
        {
            Console.Write(".");
        }

        public static bool IsUserAdministrator()
        {
            //bool value to hold our return value
            bool isAdmin = false;
            try
            {
                //get the currently logged in user
                WindowsIdentity user = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(user);
                isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch (UnauthorizedAccessException)
            {
                isAdmin = false;
            }
            catch (Exception)
            {
                isAdmin = false;
            }
            return isAdmin;
        }

        public static void RunSQLBackup()
        {
            ShowHeader();

            if (IsUserAdministrator() == true)
            {
                try
                {

                    string redirectionFolder = Directory.GetCurrentDirectory();
                    FileSystemAccessRule everyOne = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow);
                    DirectorySecurity dirSecurity = new DirectorySecurity(redirectionFolder, AccessControlSections.Group);
                    dirSecurity.AddAccessRule(everyOne);
                    Directory.SetAccessControl(redirectionFolder, dirSecurity);

                    CreateTempDir();
                    
                    WriteTimeStamp();

                    Log.Msg("SQLBackupFTP job begin");

                    if (GetScriptDB() == true)
                    {
                        SMOUtil.ScriptDBs();
                    }
                    if (GetScriptTableData() == true)
                    {
                        SMOUtil.ScriptTableData();
                    }
                    if (GetBackupDBOff() != true)
                    {
                        SQLBackup.BackupDBs();
                    }
                    if (GetSevenZipOff() != true)
                    {
                        SevenZipUtil.CompressFiles();
                    }
                    if (GetFTPOff() != true & GetSevenZipOff() != true)
                    {
                        ClientFTP.PutFiles();
                    }
                    if (GetSendMailOff() != true)
                    {
                        SendMail.SendLog();
                    }
                    DeleteTempDir();
                    tmr.Dispose();
                    Log.Msg("SQLBackupFTP job success");
                }
                catch (System.Exception ex)
                {
                    Log.Msg("SQLBackupFTP job failed", true);
                    Log.Msg(ex.ToString(), true);
                }

                ShowFooter();
                ConsoleExit();
            }
            else
            {
                Console.WriteLine("Must right click and run as Administrator");
                Console.ReadKey();
            }
        }

    }

}
